/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Controller;

import Model.Users;
import java.util.List;
import javax.faces.application.ConfigurableNavigationHandler;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.ComponentSystemEvent;
import javax.faces.model.DataModel;
import javax.faces.model.ListDataModel;
import org.primefaces.context.RequestContext;

/**
 *
 * @author Sony
 */
@ManagedBean(name = "users")
@SessionScoped
public class UserController {

    UserHelper helper;
    private Users newUser;
    DataModel lstUsers;
    private Boolean isLogin;

    public UserController() {
        helper = new UserHelper();
        newUser = new Users();
        isLogin = false;
    }

    public DataModel listUsers() {
        lstUsers = new ListDataModel(helper.getAllUser());
        return lstUsers;
    }

    public void checkLogin(ComponentSystemEvent event) {
        if (isLogin == false) {
            FacesContext context = FacesContext.getCurrentInstance();
            ConfigurableNavigationHandler handler = (ConfigurableNavigationHandler) context.getApplication().getNavigationHandler();
            handler.performNavigation("login");
        }
    }


    public String validateUser() {
        List<Users> lstUser = this.helper.getUserBy_UserName_Password(newUser.getUsername(), newUser.getPassword());
        if (lstUser.isEmpty()) {
            this.setIsLogin(false);
            FacesMessage message = new FacesMessage();
            message.setSeverity(FacesMessage.SEVERITY_ERROR);
            message.setSummary("Tên đăng nhập hoặc mật khẩu không đúng");
            message.setDetail("Tên đăng nhập hoặc mật khẩu không đúng");
            FacesContext.getCurrentInstance().addMessage("f1:txtUserName", message);
            RequestContext c = RequestContext.getCurrentInstance();
            c.update("f1");
            return "";
        } else {
            this.setIsLogin(true);
            return "loginSuccess";
        }

    }

    public void addUser() {
        helper.updateUser(newUser);
    }

    public void editUser(Users u) {
        helper.updateUser(u);
    }

    public void deleteUser(Users u) {
        helper.deleteUser(u);
    }

    /**
     * @return the newUser
     */
    public Users getNewUser() {
        return newUser;
    }

    /**
     * @param newUser the newUser to set
     */
    public void setNewUser(Users newUser) {
        this.newUser = newUser;
    }

    /**
     * @return the isLogin
     */
    public Boolean getIsLogin() {
        return isLogin;
    }

    /**
     * @param isLogin the isLogin to set
     */
    public void setIsLogin(Boolean isLogin) {
        this.isLogin = isLogin;
    }
}
